import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import logo from '@/assets/logo.png'
import styles from './index.module.scss'
import { useDispatch } from 'react-redux'
import { login } from '@/store/actions/login'
import { useHistory } from 'react-router-dom'
import { useState } from 'react'
import { useLocation } from 'react-router-dom'

export const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const [loading, setLoading] = useState(false)
  const location = useLocation()
  // console.log(location)

  const onFinish = async values => {
    // console.log(values)
    try {
      setLoading(true)
      // 等后面的登录异步 action 成功，成功之后做处理
      await dispatch(login(values))
      // 成功的提示
      message.success('登录成功', () => {
        // history.push('/home')
        const path = location?.state?.from || '/home'
        history.replace(path)
      })
      // 回调，会等提示框消失之后执行 => 跳转到首页
    } catch (e) {
      // console.log(e)
      message.error(e.response.data.message)
    }
  }
  return (
    <div className={styles.root}>
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="Logo" />
        <Form autoComplete='off' validateTrigger={['onBlur', 'onChange']} onFinish={onFinish} initialValues={{ mobile: '13911111111', code: '246810', agree: true }}>
          <Form.Item name="mobile" rules={[
            { required: true, message: '请输入手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号' }
          ]}>
            <Input placeholder='请输入手机号' size='large' />
          </Form.Item>
          <Form.Item name='code' rules={[
            { required: true, message: '请输入验证码' },
            { len: 6, message: '请输入6位验证码' }
          ]}>
            <Input.Password placeholder='请输入验证码' size='large' maxLength={6} />
          </Form.Item>
          <Form.Item name="agree" valuePropName="checked" rules={[
            {
              validator(_, value) {
                if (!value) {
                  return Promise.reject(new Error('请阅读并同意条款和协议'))
                } else { return Promise.resolve() }
              }
            }
          ]}>
            <Checkbox size='small'>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button loading={loading} type="primary" htmlType="submit" block size='large'>登录</Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
